package com.example.clientsideapplication;

import android.app.Activity;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.view.animation.Animation.AnimationListener;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.Toast;

public class MainActivity extends Activity implements AnimationListener {
	boolean menuOut = false;
	private AnimParams animParams;
	private final int LOGGED = 1; 
	private final int SLOWSPEED = 600;
	private final int FASTSPEED = 1;
	private int idMerchant;
	private double longitude, latitude;
	private String userMerchant;
	private ViewClientOfferReceiver geoReceiver;
	private IntentFilter geoFilter;
	private final String GEO_ACTION = "android.intent.action.GEO_ACTION";
	private final static int TCP_SERVER_PORT = 21111;
	private View insertOffer, viewOffer, logOut, merchantLogin, merchantSignUp, client, merchant;
	private final String SINGLE_UPDATE_ACTION = "android.intent.action.SINGLE_UPDATE_ACTION";
	private LocationManager locationManager;
	private PendingIntent pIntent;
	private BroadcastReceiver broadcastReceiver;
	private final static String MY_PREFERENCES = "myAppPref";
	private int meters;
	private Toast toast;
	private Context context;
	private int duration = Toast.LENGTH_LONG;
	private boolean pressed = false;
	private boolean firstOpening;
	private boolean isLogged;
	private SharedPreferences pref;
	private Button lastButton;
	private Boolean cacheArrayExists;
	private final static String SERVER_ADDRESS = "172.19.115.137";


	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(R.layout.main_activity);

		animParams = new AnimParams();

		pref = getSharedPreferences(MY_PREFERENCES, Context.MODE_PRIVATE);
		firstOpening =  pref.getBoolean("firstOpening", true);
		
		if(firstOpening){
			Intent intent = new Intent(this, UsersStatisticsService.class);
			intent.putExtra("serverAddress", SERVER_ADDRESS);
			intent.putExtra("serverSocket", TCP_SERVER_PORT);
			startService(intent);
		}
		isLogged=false;
		merchant = findViewById(R.id.merchant_menu);
		client = findViewById(R.id.client_menu);
		client.findViewById(R.id.slide_button).setOnClickListener(new ClickListener());
		merchantLogin = findViewById(R.id.merchant_login);
		merchantSignUp = findViewById(R.id.merchant_sign_up);
		merchantLogin.setClickable(false);
		merchantSignUp.setClickable(false);
		insertOffer = findViewById(R.id.insert_offer);
		viewOffer = findViewById(R.id.view_offer);
		logOut = findViewById(R.id.logout);
		
		insertOffer.setVisibility(View.INVISIBLE);
		viewOffer.setVisibility(View.INVISIBLE);
		logOut.setVisibility(View.INVISIBLE);
		
		lastButton = (Button)findViewById(R.id.cachingOffer);
		lastButton.setLayoutParams(new LinearLayout.LayoutParams(
                0,
               LayoutParams.MATCH_PARENT, 0.33f));
		
		context = getApplicationContext();
		guaranteeLocationFromProvider();
	}

	public void onClickSettings(View view) {
		Intent intent = new Intent(this, SettingsActivity.class);
		if(menuOut){
			doAnimation(FASTSPEED);
		}
		startActivity(intent);
	}

	public void onInsertOffer(View view) {
		Intent intent = new Intent(this, InsertOfferActivity.class);
		intent.putExtra("serverAddress", SERVER_ADDRESS);
		intent.putExtra("serverSocket", TCP_SERVER_PORT);
		if(menuOut){
			doAnimation(FASTSPEED);
		}
		startActivity(intent);
	}

	public void onViewOffer(View view) {
		Intent intent = new Intent(this, ViewMerchantOfferService.class);
		intent.putExtra("serverAddress", SERVER_ADDRESS);
		intent.putExtra("serverSocket", TCP_SERVER_PORT);
		if(menuOut){
			doAnimation(FASTSPEED);
		}
		startService(intent);
	}
	
	public void onViewCachingOffer(View view) {
		cacheArrayExists = pref.getBoolean("cacheArrayExists", false);
		if(menuOut){
			doAnimation(FASTSPEED);
		}
		if(cacheArrayExists){
			Intent intent = new Intent(this, ViewCachingOfferActivity.class);
			startActivity(intent);
		}
		else{
			toast = Toast
					.makeText(
							context,
							"Non hai ricevuto ancora nessuna offerta. Si prega di attendere il prossimo aggiornamento.",
							duration);
			toast.show();
		}
	}
	
	public void onStartWalking(View view) {
		if(menuOut){
			doAnimation(FASTSPEED);
		}
		SharedPreferences prefs = getSharedPreferences(MY_PREFERENCES, Context.MODE_PRIVATE);
		meters =  prefs.getInt("meters", 0);
		Button startButton = (Button)findViewById(R.id.start);
		Button stopButton = (Button)findViewById(R.id.stop);
		Button prefButton = (Button)findViewById(R.id.settings);
		lastButton = (Button)findViewById(R.id.cachingOffer);
		
		if(meters!=0 && !pressed){
			startButton.setVisibility(View.GONE);
			stopButton.setVisibility(View.VISIBLE);
			prefButton.setVisibility(View.GONE);
			lastButton.setLayoutParams(new LinearLayout.LayoutParams(
                             0,
                             LayoutParams.MATCH_PARENT, 0.5f));
			
			pressed = true;
			
			Intent intent = new Intent(this, GpsTransmissionService.class);
			intent.putExtra("serverAddress", SERVER_ADDRESS);
			intent.putExtra("serverSocket", TCP_SERVER_PORT);
			startService(intent);
		}
		else if(meters==0){
			toast = Toast
					.makeText(
							context,
							"Si prega di impostare il raggio minimo di azione della ricerca di offerte disponibili.",
							duration);
			toast.show();
		}
		else{
			startButton.setVisibility(View.VISIBLE);
			stopButton.setVisibility(View.GONE);
			prefButton.setVisibility(View.VISIBLE);
			lastButton.setLayoutParams(new LinearLayout.LayoutParams(
                    0,
                   LayoutParams.MATCH_PARENT, 0.33f));
			
			pressed = false;
			
			Intent intent = new Intent(this, GpsTransmissionService.class);
			stopService(intent);
		}
	}
	

	public void onMerchantLogIn(View view) {
		Intent intent = new Intent(this, MerchantLogInActivity.class);
		intent.putExtra("serverAddress", SERVER_ADDRESS);
		intent.putExtra("serverSocket", TCP_SERVER_PORT);
		merchantSignUp.setVisibility(View.GONE);
		merchantLogin.setVisibility(View.GONE);
		if(menuOut){
			doAnimation(FASTSPEED);
		}
		startActivityForResult(intent, LOGGED);
	}
	
	public void onMerchantSignUp(View view) {
		Intent intent = new Intent(this, SignUpActivity.class);
		intent.putExtra("serverAddress", SERVER_ADDRESS);
		intent.putExtra("serverSocket", TCP_SERVER_PORT);
		if(menuOut){
			doAnimation(FASTSPEED);
		}
		startActivity(intent);
	}

	public void onLogOut(View view) {
		userMerchant = null;
		idMerchant = -1;
		if(menuOut){
			doAnimation(FASTSPEED);
		}
		isLogged = false;
		Context context = getApplicationContext();
		int duration = Toast.LENGTH_SHORT;
		Toast toast = Toast.makeText(context, "Logged Out", duration);
		toast.show();
	}

	@Override
	protected void onPause() {
		unregisterReceiver(geoReceiver);
		super.onPause();
	}

	@Override
	protected void onResume() {
		geoFilter = new IntentFilter(GEO_ACTION);
		geoReceiver = new ViewClientOfferReceiver();
		registerReceiver(geoReceiver, geoFilter);

		super.onResume();
	}

	protected void onActivityResult(int requestCode, int resultCode, Intent data) {

		if (requestCode == LOGGED) {

			if (resultCode == RESULT_OK) {
				userMerchant = data.getStringExtra("userMerchant");
				idMerchant = data.getIntExtra("idMerchant", -1);
				isLogged = true;
				/*merchantLogin.setVisibility(View.GONE);
				merchantSignUp.setVisibility(View.GONE);
				insertOffer.setVisibility(View.VISIBLE);
				viewOffer.setVisibility(View.VISIBLE);
				logOut.setVisibility(View.VISIBLE);*/
				if(menuOut){
					doAnimation(FASTSPEED);
				}

				Context context = getApplicationContext();
				int duration = Toast.LENGTH_SHORT;
				Toast toast = Toast.makeText(context,
						"Welcome " + userMerchant, duration);
				toast.show();
			}

			if (resultCode == RESULT_CANCELED) {
				//merchantLogin.setVisibility(View.VISIBLE);
				//merchantSignUp.setVisibility(View.VISIBLE);
			}
		}
	}

	@Override
	public void onAnimationEnd(Animation animation) {
		menuOut = !menuOut;
		if (!menuOut) {
			merchant.setVisibility(View.INVISIBLE);
		}
		layoutApp(menuOut);
	}

	@Override
	public void onAnimationRepeat(Animation animation) {
	}

	@Override
	public void onAnimationStart(Animation animation) {
	}

	void layoutApp(boolean menuOut) {
		client.layout(animParams.left, animParams.top, animParams.right,
				animParams.bottom);
		client.clearAnimation();
	}

	private class ClickListener implements OnClickListener {
		@Override
		public void onClick(View v) {
			doAnimation(SLOWSPEED);
		}
	}
	
	private void doAnimation(int speed){
		MainActivity me = MainActivity.this;
		Animation anim;
		final float sizeSlide = (float) 0.6; // cambia qui per modificare lo Slide
		int width = client.getMeasuredWidth();
		int height = client.getMeasuredHeight();
		int left = (int) (client.getMeasuredWidth() * sizeSlide); 
		
		if (!menuOut) {
			
			if(isLogged){
				merchantLogin.setVisibility(View.GONE);
				merchantSignUp.setVisibility(View.GONE);
				merchantLogin.setClickable(false);
				merchantSignUp.setClickable(false);
				insertOffer.setVisibility(View.VISIBLE);
				viewOffer.setVisibility(View.VISIBLE);
				logOut.setVisibility(View.VISIBLE);
				insertOffer.setClickable(true);
				viewOffer.setClickable(true);
				logOut.setClickable(true);
			}else{
				merchantLogin.setVisibility(View.VISIBLE);
				merchantSignUp.setVisibility(View.VISIBLE);
				insertOffer.setVisibility(View.GONE);
				viewOffer.setVisibility(View.GONE);
				logOut.setVisibility(View.GONE);
				merchantLogin.setClickable(true);
				merchantSignUp.setClickable(true);
				insertOffer.setClickable(false);
				viewOffer.setClickable(false);
				logOut.setClickable(false);
			}
			anim = new TranslateAnimation(0, left, 0, 0);
			merchant.setVisibility(View.VISIBLE);
			animParams.init(left, 0, left + width, height);
		} else {
			merchantLogin.setClickable(false);
			merchantSignUp.setClickable(false);
			insertOffer.setClickable(false);
			viewOffer.setClickable(false);
			logOut.setClickable(false);

			anim = new TranslateAnimation(0, -left, 0, 0);
			animParams.init(0, 0, width, height);
		}
		anim.setDuration(speed);
		anim.setAnimationListener(me);
		anim.setFillAfter(true);
		client.startAnimation(anim);
	}

	static class AnimParams {
		int left, right, top, bottom;

		void init(int left, int top, int right, int bottom) {
			this.left = left;
			this.top = top;
			this.right = right;
			this.bottom = bottom;
		}
	}
	
	/**
	 * Try to get the "best" location selected from all providers
	 */
	private void guaranteeLocationFromProvider() {
	    boolean networkIsEnabled;
		
		locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
		networkIsEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
		
		if(networkIsEnabled){
			pIntent = PendingIntent.getBroadcast(context,
                    0,
                    new Intent(SINGLE_UPDATE_ACTION),
                    PendingIntent.FLAG_UPDATE_CURRENT);
			
			IntentFilter iFilter = new IntentFilter(SINGLE_UPDATE_ACTION);
			
			broadcastReceiver = new BroadcastReceiver(){
                
				@Override
				public void onReceive(Context context, Intent intent) {
            		Toast toast;
            		int duration = Toast.LENGTH_LONG;
            		
                    // When received an answer from the LocationManager
                    Location networkLocation = (Location) intent.getExtras().get(LocationManager.KEY_LOCATION_CHANGED);
                    latitude = networkLocation.getLatitude();
                    longitude = networkLocation.getLongitude();

                    locationManager.removeUpdates(pIntent);
                    unregisterReceiver(broadcastReceiver);
                    
                    toast = Toast
        					.makeText(
        							context,
        							"Localizzazione network aggiornata!",
        							duration);
        			toast.show();
                }
			};
			
            registerReceiver(broadcastReceiver, iFilter);
            
            locationManager.requestSingleUpdate(LocationManager.NETWORK_PROVIDER, pIntent);
	    	
	    	toast = Toast
					.makeText(
							context,
							"Per una migliore localizzazione si consiglia di attivare il GPS prima di effettuare l'eventuale ricerca.",
							duration);
			toast.show();
	    }
		else{	    	
	    	toast = Toast
					.makeText(
							context,
							"Si prega di attivare la connessione dati.",
							duration);
			toast.show();
	    }
		
	}

}
